/**
 * @project heima-leadnews
 * @author MECHREVO
 * @date 2024/1/18 10:32:18
 * @version 1.0
 */
package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.file.service.FileStorageService;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.HttpUtil;
import com.heima.wemedia.service.BaiduScanService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class BaiduScanServiceImpl implements BaiduScanService {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 百度云内容审核-审核文本
     *
     * @param text
     * @return
     */
    @Override
    public Map<String, Object> scanText(String text) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken=(String) stringRedisTemplate.opsForValue().get("accessToken");
            if(StringUtils.isEmpty(accessToken)){
                accessToken=getAccessToken();
                stringRedisTemplate.opsForValue().set("accessToken",accessToken,10, TimeUnit.DAYS);
            }

            String result = HttpUtil.post(url, accessToken, param);

            return JSON.parseObject(result,Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,Object>res=new HashMap<>();
        res.put("conclusionType",3);
        return res;
    }

  /*  @Scheduled(cron = "0 0 0 1/10 * ?")
    @PostConstruct
    public void refreshToken() {
        log.info("-------定时刷新百度云accessToken");
        localStorage.clear();
    }*/

    /**
     * 百度云内容审核-审核图片
     *
     * @param Imgurl
     * @return
     */
    @Override
    public Map<String, Object> scanImg(String Imgurl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            // 本地文件路径

            byte[] imgData = fileStorageService.downLoadFile(Imgurl);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken=(String) stringRedisTemplate.opsForValue().get("accessToken");
            if(StringUtils.isEmpty(accessToken)){
                accessToken=getAccessToken();
                stringRedisTemplate.opsForValue().set("accessToken",accessToken,10,TimeUnit.DAYS);
            }

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return JSON.parseObject(result,Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,Object>res=new HashMap<>();
        res.put("conclusionType",3);
        return res;
    }

    static final OkHttpClient HTTP_CLIENT=new OkHttpClient().newBuilder().build();
    private String getAccessToken(){
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=ldtCQGGne4AvW90goIzfDYcd&client_secret=BmyefQlkXHKoUFC5DXHvGBfpwEoiKXrb&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            return jsonObject.getString("access_token");
        } catch (IOException e) {
            return null;
        }
    }
}
